package com.astrob.activitys;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.astrob.NavFrameSDK;
import com.astrob.NavFrameSDK.CLonLat;
import com.astrob.NavFrameSDK.GuideInfo;
import com.astrob.NavFrameSDK.NavPosition;
import com.astrob.NavFrameSDK.POIDescription;
import com.astrob.NavFrameSDK.TurnInfo;
import com.astrob.adapters.TurnAdapter;
import com.astrob.model.BaseTurn;
import com.astrob.model.HistoryData;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.model.RoutePlanDataHandle;
import com.astrob.model.SortByDistance;
import com.astrob.model.SystemSetFileHandle;
import com.astrob.model.TurnItem;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.Utils;
import com.astrob.view.Car;
import com.astrob.view.MapView;
import com.astrob.view.ZoomView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class NewRouteInfoActivity extends Activity {

	private List<TurnItem> mTurnList;
	private TurnAdapter mTurnAdapter;
	private ListView mRInfoListview;

	private TextView mStartT;
	private TextView mDestT;
	private TextView mDistance;
	private TextView mAlltime;

	private MapView mMapView = null;
	private ZoomView mZoom = null;
	private FrameLayout mMapctrl = null;
	private TextView mScale = null;
	protected Car mCar = new Car();
	
	RadioGroup mGroupRouteMethod;
	RadioButton mRadioCar;
	RadioButton mRadioWalk;
	
	private ArrayList<LonLat> mTurnPosList = new ArrayList<LonLat>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newroute_info);

		mStartT = (TextView) findViewById(R.id.id_routeinfo_start);
		mDestT = (TextView) findViewById(R.id.id_routeinfo_dest);
		mRInfoListview = (ListView) findViewById(R.id.lv_routeinfo_list);
		mRInfoListview.setVerticalScrollBarEnabled(false);
		mDistance = (TextView) findViewById(R.id.id_routeinfo_allinfo);
		mAlltime = (TextView) findViewById(R.id.id_routeinfo_alltime);

		mMapctrl = (FrameLayout) this.findViewById(R.id.id_mapctrl);
		mMapView = (MapView) this.findViewById(R.id.id_mapview);
		mZoom = (ZoomView) findViewById(R.id.id_zoomview);
		mScale = (TextView) findViewById(R.id.id_map_scalebar);
		mScale.setText(Start.getInstance().MapKit().getScaleString());

		mGroupRouteMethod = (RadioGroup) findViewById(R.id.radioGroupRouteMethod);
		mRadioCar = (RadioButton) findViewById(R.id.radioCar);
		mRadioWalk = (RadioButton) findViewById(R.id.radioWalk);
		
		double dlon = SystemSetFileHandle.getInstance().getSystemSet().previewLon;
		double dlat = SystemSetFileHandle.getInstance().getSystemSet().previewLat;
		NavPosition matchCar = mCar.getCarNavPos();
		matchCar.pos.lon = dlon;
		matchCar.pos.lat = dlat;
		matchCar.signal = 100;
		mCar.setCarNavPos(matchCar);
		mCar.setFreeMoving(true);
		mMapView.setCar(mCar);

		initAll();
		
		Bundle extra = getIntent().getExtras();
		if(extra != null) {
			boolean noTurnLimit = extra.getBoolean("noTurnLimit", false);
			if(noTurnLimit) {
				new AlertDialog.Builder(this)
				.setTitle(getString(R.string.dlg_title))
				.setMessage("此路线部分目的地无法开车到达，请注意交通标志行驶! ")
				.setPositiveButton("确认", null)
				.show();
			}
		}
	}

	private void initAll() {		
		setRouteRadio(Start.getInstance().MapKit().isCarRouteOption());
		
		String strDest = "";
		String startName = Start.getInstance().MapKit().mNavStart.name;
		if (startName == null || startName.length() == 0) {
			if (Start.getInstance().MapKit().mNavStart.pos.lon == 0) {
				startName = getString(R.string.the_current_position);
			} else {
				LonLat ll = new LonLat(Start.getInstance().MapKit().mNavStart.pos.lon,
						Start.getInstance().MapKit().mNavStart.pos.lat);
				Start.getInstance().MapKit().mTipPoiList = Start.getInstance()
						.MapKit().getNearPoi(ll, false);
				if (Start.getInstance().MapKit().mTipPoiList.size() > 0) {
					POIDescription poiData = Start.getInstance().MapKit().mTipPoiList
							.get(0);
					startName = poiData.name;
				} else {
					startName = (float) ll.GetLon() + " " + (float) ll.GetLat();
				}
			}
		}

		startName = startName.replace("\n", " ");
		mStartT.setText(startName);
		if (Start.getInstance().MapKit().mNavDest != null) {
			int index = Start.getInstance().MapKit().mNavDest.length - 1;
			strDest = Start.getInstance().MapKit().mNavDest[index].name;
		}
		strDest = strDest.replace("\n", " ");
		mDestT.setText(strDest);

		if (mTurnList == null) {
			mTurnList = new ArrayList<TurnItem>();
		}

		if (mTurnAdapter == null) {
			mTurnAdapter = new TurnAdapter(this);
		}

		mTurnAdapter.setDataList(mTurnList);
		mRInfoListview.setAdapter(mTurnAdapter);
		mRInfoListview
				.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
											int position, long id) {
						onTurnPos(position);
					}
				});
		
		setTurnList();
		selectMode(true);
	}

	private void setRouteRadio(boolean isCarRouteOption) {
		if (isCarRouteOption) {
			mRadioCar.setChecked(true);
			mRadioWalk.setChecked(false);
		} else {
			mRadioCar.setChecked(false);
			mRadioWalk.setChecked(true);	
		}		
	}

	protected void onTurnPos(int pos) {
		int size = mTurnPosList.size();
		if (size < 1) {
			return;
		}
		
		if (pos < 0) {
			pos = 0;
		}
		
		if (pos >= size) {
			pos = size - 1;
		}

		Intent intent = new Intent(this, NaviActivity.class);
		intent.putExtra("mapcenterlon", mTurnPosList.get(pos).GetLon()); //
		intent.putExtra("mapcenterlat", mTurnPosList.get(pos).GetLat());
		intent.putExtra("showOnmap", true);
		startActivityForResult(intent, Msg.REQUEST_SHOW_ON_MAP);
	}

	public void onClickedSimu(View v) {
		if (Utils.isFastDoubleClick())
			return;

		setResult(Msg.NAVI_SIMU);
		finish();
	}

	public void onClickedNavi(View v) {
		if (Utils.isFastDoubleClick())
			return;
		
		setResult(Msg.NAVI_TONAVI);
		finish();
	}

	protected void showHint(String hint) {
		Toast.makeText(this, hint, Toast.LENGTH_SHORT).show();
	}

	public void onSaveRoute(View v) {
		if (Utils.isFastDoubleClick())
			return;

		HistoryData start = RoutePlanDataHandle.getInstance().getStart();
		if (start == null || start.lon == 0) {
			showHint(getString(R.string.routemanager_select_curpos_start));
			// return;
			start = new HistoryData();
			double dlon = SystemSetFileHandle.getInstance().getSystemSet().previewLon;
			double dlat = SystemSetFileHandle.getInstance().getSystemSet().previewLat;
			start.lon = dlon;
			start.lat = dlat;
			start.name = getString(R.string.the_current_position);

			start.setLl(Start.getInstance().MapKit().getMapCenter());
			start.setName(getString(R.string.the_current_position));
			RoutePlanDataHandle.getInstance().setStart(start);
		}
		RoutePlanDataHandle.getInstance().setDestsfromNavDest();
		ArrayList<HistoryData> hisDests = RoutePlanDataHandle.getInstance()
				.getDests();

		int count = hisDests.size();
		if (count <= 0) {
			showHint(getString(R.string.routemanagement_requires_at_least_one_destination));
			return;			
		}

		ArrayList<HistoryData> dests = new ArrayList<HistoryData>();
		if (start.getName() == getString(R.string.the_current_position)) {
			// 修改start name
			ArrayList<POIDescription> pois = Start.getInstance().MapKit().getNearPoi(
					start.getLl(), false);
			if (pois != null && pois.size() > 0) {
				Collections.sort(pois, new SortByDistance());
				POIDescription local = pois.get(0);
				start.setName(local.name);
			}
		}
		dests.add(start);
		for (int i = 0; i < count; ++i) {
			dests.add(hisDests.get(i));
		}
		RoutePlanDataHandle.getInstance().load(this);
		boolean ret = RoutePlanDataHandle.getInstance().addRoutePlan(dests,
				null);
		RoutePlanDataHandle.getInstance().close();
		if (ret) {
			showHint(getString(R.string.routemanagement_has_been_saved));
		}
	}

	public void onZoomIn(View v) {
		Start.getInstance().MapKit().onZoomIn();
		updateMapView();
	}

	public void onZoomOut(View v) {
		Start.getInstance().MapKit().onZoomOut();
		updateMapView();
	}

	private void updateMapView() {
		mMapView.invalidate();
		mScale.setText(Start.getInstance().MapKit().getScaleString());
	}

	private int startindex = 0;

	protected void setTurnList() {
		boolean isSimu = true;
	/*	if (PositionProvider.getInstance().getProviderMode() == PositionProvider.PATHSIMU_PROVIDER) {
			isSimu = true;
		}*/

		int totaldistance = 0;
		try {
			if (isSimu) {
				if (!Start.getInstance().MapKit().prepareTurnAndGuid())
					return;
			} else {
				if (Start.getInstance().MapKit().prepareCurTurnAndGuid() < 0) {
					if (!Start.getInstance().MapKit().prepareTurnAndGuid())
						return;
				}
			}

			startindex = 0;

			int index = 0;
			int lastIcon = 0;
			String lastToRoadName = "";
			String metroEndName = ""; //几号出口
			String distance = "";
			if (mTurnList != null && !mTurnList.isEmpty()) {
				mTurnList.clear();
			}
			boolean haveMetro = false;
			mTurnPosList.clear();

			while (true) {
				TurnInfo turnInfo = NavFrameSDK.getInstance().new TurnInfo();
				GuideInfo guidInfo = NavFrameSDK.getInstance().new GuideInfo();
				CLonLat pPos = NavFrameSDK.getInstance().new CLonLat();
				if (!Start.getInstance().MapKit().nextTurnAndGuid(turnInfo, guidInfo,
						pPos))
					break;
				LonLat turnPos = new LonLat(pPos.lon, pPos.lat);
				mTurnPosList.add(turnPos);

				distance = Start.getInstance().MapKit().getDistanceString(
						(int) guidInfo.distanceToTurn);
				totaldistance += (int) guidInfo.distanceToTurn;

				BaseTurn turn = new BaseTurn(lastToRoadName, lastIcon, distance);
				mTurnList.add(turn);

				lastIcon = getListIconId(turnInfo);
				lastToRoadName = turnInfo.toRoadName;
				lastToRoadName = lastToRoadName.replace(".", " ");
				if (lastToRoadName.length() < 1) {
					lastToRoadName = getString(R.string.routeinfo_noname);
				}
				index++;
			}


			Start.getInstance().MapKit().finishTurnAndGuid();
			modifyLastTurn();

		} catch (Exception e) {
		}

		setTotal(Start.getInstance().MapKit().getDistanceString(totaldistance),
				getTotalTime(totaldistance, 0, 0, 80, 40));
	}

	//"到达%s，离开%s" ->
	//到达%s
	private String setNameforMetroEnd(String fromRoadName) {
		String metroEndName = "";
		if (fromRoadName == null) {
			return metroEndName;
		}

		if (fromRoadName.contains("，")) {
			String[] xxName = fromRoadName.split("，");
			metroEndName = xxName[0].replace("到达", "");
		}

		LonLat destLL = new LonLat();
		if (Start.getInstance().MapKit().mNavDest != null
				&& Start.getInstance().MapKit().mNavDest.length > 0) {
			destLL.SetLonLat(Start.getInstance().MapKit().mNavDest[0].pos.lon,
					Start.getInstance().MapKit().mNavDest[0].pos.lat);
		}

		return metroEndName;
	}

	private void setTotal(String totalDistance, String totalCost) {
		mDistance.setText("总距离:" + totalDistance);
		mAlltime.setText("总时间: " + totalCost);
	}

	private String getTotalTime(int totalDistance, int metroDistance, int totalhwdis, int hwspeed,
								int normalspeed) {
		String totalTime = "";

		// km/h - > m/s
		hwspeed = hwspeed * 1000 / 3600;
		normalspeed = normalspeed * 1000 / 3600;
		int metroSpeed = 40 * 1000 / 3600;

		long ArrivalTime;

		if (totalhwdis <= totalDistance)
			ArrivalTime = (long) ((totalDistance - totalhwdis) / normalspeed)
					+ (long) (totalhwdis / hwspeed);
		else
			// 正常情况下不会走到该case
			ArrivalTime = (totalDistance / hwspeed);

		if (!Start.getInstance().MapKit().mRouteOption.bFastest) {
			// 步行速度 3 米/秒
			ArrivalTime = (int)(totalDistance / 0.8);
		}
		
		ArrivalTime += (metroDistance / metroSpeed);

		long hour = ArrivalTime / 3600;
		long minute = (ArrivalTime - hour * 3600) / 60;
		if (hour > 0) {
			totalTime = hour + " " + "h ";
		}
		
		if (hour < 10) {
			if (minute > 0)
				totalTime += minute + " min";
			else if (hour <= 0)
				totalTime = 1 + " min";
		}

		return totalTime;
	}

	private int getListIconId(TurnInfo turnInfo) {
		int dirType = 0;
		boolean haveTrueDir = false;
		if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_STRAIGHT_SAME) {
			dirType = R.drawable.turn2_straight;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_UTURN) {
			dirType = R.drawable.turn2_uturnleft;
			haveTrueDir = true;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_ONLYLEFT) {
			dirType = R.drawable.turn2_keepleft;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_ONLYRIGHT) {
			dirType = R.drawable.turn2_keepright;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_LEFTBEAR) {
			dirType = R.drawable.turn2_bearleft;
			haveTrueDir = true;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_RIGHTBEAR) {
			dirType = R.drawable.turn2_bearright;
			haveTrueDir = true;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_LEFT) {
			dirType = R.drawable.turn2_turnleft;
			haveTrueDir = true;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_RIGHT) {
			dirType = R.drawable.turn2_turnright;
			haveTrueDir = true;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_LEFTFRONT) {
			dirType = R.drawable.turn2_turnleft;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_RIGHTFRONT) {
			dirType = R.drawable.turn2_turnright;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_END) {
			dirType = R.drawable.turn2_arriveend;
			haveTrueDir = true;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_3FORK) {
			dirType = R.drawable.turn2_bif_middle;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_3FORKONLYLEFT) {
			dirType = R.drawable.turn2_bif_left;
			haveTrueDir = true;
		} else if (turnInfo.dirType == NavFrameSDK.TurnDirection.TURN_3FORKONLYRIGHT) {
			dirType = R.drawable.turn2_bif_right;
			haveTrueDir = true;
		}

		if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_MAIN2AUX) {
			if (!haveTrueDir)
				dirType = R.drawable.turn2_enterserviceroad;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_AUX2MAIN) {
			if (!haveTrueDir)
				dirType = R.drawable.turn2_leaveserviceroad;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_ENTERRAMP) {
			// dirType = R.drawable.turn_enterramp;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_ENTERHWY) {
			dirType = R.drawable.turn2_freeway;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_EXITFERRY) {
			dirType = R.drawable.turn2_leaveferry;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_ENTERSERVICES) {
			dirType = R.drawable.turn2_enterservice;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_EXITHWY) {
			// dirType = R.drawable.turn_leaveramp;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_TOLL) {
			dirType = R.drawable.turn2_toll;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_ENTERFERRY) {
			dirType = R.drawable.turn2_enterferry;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_ENTERTUNNEL) {
			dirType = R.drawable.turn2_tunnel;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_ENTERCIRCLE) {
			dirType = R.drawable.turn2_roundabout;
		} else if (turnInfo.categoryChange == NavFrameSDK.CategoryChangeType.TURN_EXITCIRCLE) {
			dirType = R.drawable.turn2_roundabout;
		}

		return dirType;
	}

	/**
	 * 最后一个转弯修改为终点
	 */
	private void modifyLastTurn() {
		BaseTurn turn = new BaseTurn(getString(R.string.zhongdian),
				R.drawable.turn_arriveend, "");
		mTurnList.add(turn);
	}
	
	public void onCarRoute(View v) {
		if (Utils.isFastDoubleClick() || mIsRouting)
			return;
		if (Start.getInstance().MapKit().isCarRouteOption()) {
			setRouteRadio(true);
			return;
		}

		new AlertDialog.Builder(this).setTitle(getString(R.string.dlg_title))
				.setMessage("将按行车模式重新规划路线。")
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Start.getInstance().MapKit().setCarRouteOption();
						mHandler.sendEmptyMessage(Msg.BEGINROUTE);
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						setRouteRadio(false);
					}
				})
				.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						setRouteRadio(false);
					}
				}).show();

	}

	public void onWalkRoute(View v) {
		if (Utils.isFastDoubleClick() || mIsRouting)
			return;
		if (!Start.getInstance().MapKit().isCarRouteOption()) {
			setRouteRadio(false);
			return;
		}
		new AlertDialog.Builder(this).setTitle(getString(R.string.dlg_title))
				.setMessage("将按步行模式重新规划路线。")
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Start.getInstance().MapKit().setWalkRouteOption();
						mHandler.sendEmptyMessage(Msg.BEGINROUTE);
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						setRouteRadio(true);
					}
				})
				.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						setRouteRadio(true);
					}
				}).show();
	}
	
	private ProgressDialog mPB = null;
	private boolean mIsRouting = false;
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Msg.BEGINROUTE:
				onRoute();
				break;
			case Msg.FINISHROUTE:
				onFinishRoute();
				break;
			}
		}
	};

	private void onRoute() {
		if (mIsRouting) {
			return;
		}
		
		mPB = new ProgressDialog(this);
		mPB.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mPB.setMessage(getString(R.string.navi_routing_progress));
		mPB.setCancelable(false);
		mPB.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface arg0) {
			}
		});

		mPB.setMax(100);
		mPB.setProgress(0);
		mPB.show();

		mIsRouting = true;
		new Thread() {
			@Override
			public void run() {
				if (Start.getInstance().MapKit().mNavStart.pos.lon == 0) {
					Start.getInstance().MapKit().mNavStart.pos.lon = SystemSetFileHandle.getInstance().getSystemSet().previewLon;
					Start.getInstance().MapKit().mNavStart.pos.lat = SystemSetFileHandle.getInstance().getSystemSet().previewLat;
				}
				Start.getInstance().MapKit().route(Start.getInstance().MapKit().mNavStart,
						Start.getInstance().MapKit().mNavDest, null);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(Msg.FINISHROUTE);
			}
		}.start();

		Timer processTimer = new Timer();
		processTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				int process = Start.getInstance().MapKit().getRoutingProcess();
				if (mPB != null) {
					mPB.setProgress(process);
				} else {
					cancel();
				}
			}
		}, 500, 500);
	}
	
	private void onFinishRoute() {
		mIsRouting = false;
		if (mPB != null) {
			mPB.dismiss();
			mPB = null;
		}
		mIsRouting = false;
		initAll();
	}

	public void onBack(View v) {
		setResult(Msg.BACK_MAP_ID);
		finish();
	}

	public void onToMapmode(View v) {
		selectMode(true);
	}

	public void selectMode(boolean isMap) {
		if (isMap) {
			mMapctrl.setVisibility(View.VISIBLE);
			findViewById(R.id.btn_route_info_ctrl).setVisibility(View.GONE);
			findViewById(R.id.btn_tomapmode).setVisibility(View.GONE);
			findViewById(R.id.btn_tolistmode).setVisibility(View.VISIBLE);
			showFullPath();
		} else {
			mMapctrl.setVisibility(View.GONE);
			findViewById(R.id.btn_route_info_ctrl).setVisibility(View.VISIBLE);
			findViewById(R.id.btn_tomapmode).setVisibility(View.VISIBLE);
			findViewById(R.id.btn_tolistmode).setVisibility(View.GONE);
		}
	}

	void showFullPath() {
		Start.getInstance().MapKit().setRotation(0);
		Start.getInstance().MapKit().showFullPath();
		updateMapView();
	}

	public void onToListmode(View v) {
		selectMode(false);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mMapView.onMouseEvent(event);

		if (event.getAction() == MotionEvent.ACTION_UP) {
			updateMapView();
		} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
			updateMapView();
		}

		return super.onTouchEvent(event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			setResult(Msg.BACK_MAP_ID);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void finish() {
		// 主页面需重置mapbuffer
		mMapView.resetBuffer();
		super.finish();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
}
